from django.db.models import Count
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from .models import PreRepairLog
from .serializers import PreRepairLogSerializer, RepairRateSerializer


class PreRepairLogViewSet(viewsets.ModelViewSet):
    '''
    list: 查询所有PreRepairLog
    create: 新增PreRepairLog
    retrieve: 查询单个PreRepairLog, 文档名: read,接口名: retrieve
    update: 更新PreRepairLog
    destroy: 删除PreRepairLog
    '''
    queryset = PreRepairLog.objects.all()
    serializer_class = PreRepairLogSerializer

    @action(detail=False, methods=['get'])
    def repair_rate(self, request):
        queryset = PreRepairLog.objects.all().values(
            'equipment__category__name').annotate(count=Count('id'))
        total_count = PreRepairLog.objects.all().count()
        use_rate = [{
            'category': item['equipment__category__name'],
            'use_rate': item['count'] / total_count * 100
        } for item in queryset]
        serializer = RepairRateSerializer(use_rate, many=True)
        return Response(serializer.data)
